package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;



    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    public Boolean selectByName(Long id, String name) {
        Role role = roleMapper.selectByName(name);
        return role==null||role.getId()==id;
    }

    public void saveOrUpdate(Role role) {
        /*维护关系*/
        if (role.getId() == null) {
            roleMapper.insert(role);
        }else{
            roleMapper.deleteMenuRelation(role.getId());
            roleMapper.deletePermissionRelation(role.getId());
            roleMapper.updateByPrimaryKey(role);
        }

        List<Permission> permissions = role.getPermissions();
        if (permissions!=null) {
            for (Permission p : permissions) {
                roleMapper.insertPermissionRelation(role.getId(),p.getId());
            }
        }
        List<Menu> menus = role.getMenus();
        if (menus!=null) {
            for (Menu menu : menus) {
                roleMapper.insertMenuRelation(role.getId(),menu.getId());
            }
        }
    }

    public void delete(Long id) {
        if(id!=null){
            roleMapper.deleteByPrimaryKey(id);
        }
    }

    public List<Long> selectByEmpId(Long id) {
        return roleMapper.selectByEmpId(id);
    }

    public Collection<String> selectNameByEmpId(Long empId) {
        return roleMapper.selectNameByEmpId(empId);
    }
}
